package sensor

import (
	//"encoding/binary"
	//"fmt"
	"strings"
	"time"
	"unicode"
	//"log"
	//"math"
)

// NewParser 创建解析器（根据传感器类型）
func NewParser(sensorType string, dataLength int) DataParser {
	switch sensorType {
	case "temperature_humidity":
		return NewTemperatureHumidityParser(dataLength)
	case "temperature_only":
		return NewTemperatureOnlyParser(dataLength)
	case "temperature":
		return NewTemperatureOnlyParser(dataLength)
	case "co":
		return NewCOParser(dataLength)
	case "co2":
		return NewCO2Parser(dataLength)
	case "smoke":
		return NewSmokeParser(dataLength)
	case "conductivity":
		return NewElecParser(dataLength)
	case "liquid_level":
		return NewLevelParser(dataLength)
	case "flow":
		return NewFlowParser(dataLength)
	default:
		return NewDefaultParser(dataLength)
	}
}

// DefaultParser 默认解析器
type DefaultParser struct {
	expectedLength int
}

func NewDefaultParser(dataLength int) *DefaultParser {
	return &DefaultParser{
		expectedLength: dataLength,
	}
}

func (p *DefaultParser) Validate(data []byte) bool {
	return len(data) >= p.expectedLength
}

func (p *DefaultParser) Parse(data []byte) (*SensorData, error) {
	return &SensorData{
		SensorType: "unknown",
		Values: map[string]interface{}{
			"raw_value": string(data),
		},
		RawData:   string(data),
		Timestamp: time.Now(),
	}, nil
}

// 辅助函数：清理字符串
func cleanString(s string) string {
	return strings.TrimFunc(s, func(r rune) bool {
		return !unicode.IsDigit(r) && r != '.'
	})
}
